﻿using System;
using System.Text;
using System.IO;
using System.Xml;
using System.IO.IsolatedStorage;

namespace GoogleLogger
{
    public class XmlConfig
    {
        private const string ConfigContent = @"<?xml version=""1.0"" encoding=""utf-8"" ?> 
                    <config>
                      <user>
                        <UserName></UserName>
                        <SavePassWord></SavePassWord>
                        <PassWord></PassWord>
                      </user>
                      <Calendar>
                        <LastCalendarSet></LastCalendarSet>
                      </Calendar>
                    </config> ";
        private static string ConfigPatch = Directory.GetCurrentDirectory() + @"\MyGoogleCalender2.xml";

        protected static bool CheckConfigDoctory()
        {
            string ConfigDirectoryPath = Directory.GetCurrentDirectory();
            if (!Directory.Exists(ConfigDirectoryPath))
            {
                Directory.CreateDirectory(ConfigDirectoryPath);
                return false;
            }
            else
            {
                if (!File.Exists(ConfigPatch))
                {
                    return false;
                }
                return true;
            }
        }
        protected static bool CheckConfigFile()
        {

            bool ret = false;
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForDomain();
            try
            {                
                string[] filenames = isf.GetFileNames("MyGoogleCalender2.xml");

                foreach (string storefile in filenames)
                {
                    if (storefile == "MyGoogleCalender2.xml")
                    {
                        bool ConfigError = false;
                        XmlTextReader Xreader_Schema = new XmlTextReader(new StringReader(ConfigContent));
                        XmlTextReader XReader_Config = new XmlTextReader(new IsolatedStorageFileStream(storefile, FileMode.Open, isf));
                        XReader_Config.WhitespaceHandling = WhitespaceHandling.None;
                        Xreader_Schema.WhitespaceHandling = WhitespaceHandling.None;

                        while (Xreader_Schema.Read())
                        {
                            while (XReader_Config.Read())
                            {
                                if (XReader_Config.NodeType == XmlNodeType.Element ||
                                    XReader_Config.NodeType == XmlNodeType.EndElement ||
                                    XReader_Config.NodeType == XmlNodeType.XmlDeclaration)
                                { break; }
                            }
                            if ((Xreader_Schema.NodeType != XReader_Config.NodeType) || (Xreader_Schema.Name != XReader_Config.Name))
                            {
                                ConfigError = true;
                                break;
                            }
                        }
                        Xreader_Schema.Close();
                        XReader_Config.Close();
                        isf.Close();
                        ret = !ConfigError;
                    }
                }
            }

            catch
            {
                isf.Close();
                ret = false;
            }
            return ret;

        }


        public static void CheckConfig()
        {
            if (!XmlConfig.CheckConfigFile())
            {
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForDomain();
                IsolatedStorageFileStream stmWrite = new IsolatedStorageFileStream("MyGoogleCalender2.xml", FileMode.Create, isf);
                
                XmlDocument Xdoc = new XmlDocument();
                Xdoc.LoadXml(ConfigContent);
                XmlTextWriter Xwrite = new XmlTextWriter(stmWrite, System.Text.Encoding.UTF8);
                Xdoc.Save(Xwrite);
                Xwrite.Flush();
                stmWrite.Flush();
                Xwrite.Close();
                stmWrite.Close();
                isf.Close();
            }
        }
        public struct userInfo
        {
            public string userName;
            public bool SavePassWord;
            public string userPassword;
        }
        protected static string ISSavePassWord()
        {
            XmlDocument Xdoc = new XmlDocument();
            Xdoc.Load(ConfigPatch);
            XmlNodeList XnodeList = Xdoc.SelectNodes("config/user/UserName");
            //if (Boolean.Parse(XnodeList.Item(1).Value))
            //{

            //}
            return XnodeList.Item(0).InnerText;
        }
        public static userInfo GetUserInfo()
        {
            CheckConfig();
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForDomain();
            IsolatedStorageFileStream stmRead = new IsolatedStorageFileStream("MyGoogleCalender2.xml", FileMode.Open, isf);
            userInfo User = new userInfo();
            XmlDocument Xdoc = new XmlDocument();
            Xdoc.Load(stmRead);
            XmlNodeList XnodeList = Xdoc.SelectSingleNode("config/user").ChildNodes;
            if (XnodeList.Count == 3
                && XnodeList.Item(0).Name == "UserName"
                && XnodeList.Item(1).Name == "SavePassWord"
                && XnodeList.Item(2).Name == "PassWord")
            {
                bool ISSavePassWord;
                User.userName = XnodeList.Item(0).InnerText;
                if (bool.TryParse(XnodeList.Item(1).InnerText, out ISSavePassWord))
                {
                    User.SavePassWord = ISSavePassWord;
                }
                if (User.SavePassWord)
                {
                    User.userPassword = XnodeList.Item(2).InnerText;
                }
            }
            stmRead.Close();
            isf.Close();
            return User;
        }
        public static void SaveUserInfo(userInfo User)
        {
            CheckConfig();
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForDomain();
            IsolatedStorageFileStream stmWrite = new IsolatedStorageFileStream("MyGoogleCalender2.xml", FileMode.Create, isf);
            XmlDocument Xdoc = new XmlDocument();
            Xdoc.LoadXml(ConfigContent);
            XmlNodeList XnodeList = Xdoc.SelectSingleNode("config/user").ChildNodes;
            if (XnodeList.Count == 3
                && XnodeList.Item(0).Name == "UserName"
                && XnodeList.Item(1).Name == "SavePassWord"
                && XnodeList.Item(2).Name == "PassWord")
            {

                XnodeList.Item(0).InnerText = User.userName;
                XnodeList.Item(1).InnerText = User.SavePassWord.ToString();
                if (User.SavePassWord)
                {
                    XnodeList.Item(2).InnerText = User.userPassword;
                }
                else
                {
                    XnodeList.Item(2).InnerText = "";
                }
            }
            Xdoc.Save(stmWrite);
            stmWrite.Flush();
            stmWrite.Close();
            isf.Close();
        }
        public static string GetLastCalendarSelect()
        {
            XmlDocument Xdoc = new XmlDocument();
            string Ret;
            Xdoc.Load(ConfigPatch);
            try
            {
                Ret = Xdoc.SelectSingleNode("config/Calendar/LastCalendarSet").InnerText;
            }
            catch
            {
                Ret = "";
            }

            return Ret;
        }
        public static void Save_LastCalendarSelect(string CalendarName)
        {
            CheckConfig();
            XmlDocument Xdoc = new XmlDocument();
            Xdoc.Load(ConfigPatch);
            Xdoc.SelectSingleNode("config/Calendar/LastCalendarSet").InnerText = CalendarName;
            Xdoc.Save(ConfigPatch);
        }
    }
}

